package org.zoomdev.zoom.dao.entity;

import org.zoomdev.zoom.dao.DaoException;

public final class TableSource {

    private final String table;

    private final String alias;

    public TableSource(String table, String alias) {
        this.table = table;
        this.alias = alias;
    }

    public static TableSource[] fromArray(String... src) {
        TableSource[] dest = new TableSource[src.length];
        for (int i = 0; i < src.length; ++i) {
            dest[i] = from(src[i]);
        }
        return dest;
    }

    public static TableSource from(String src) {
        String table;
        String alias;
        if (src.contains(" ")) {
            String[] parts = src.split("\\s+");
            if (parts.length != 2) {
                throw new DaoException("table格式不正确:" + src);
            }
            table = parts[0];
            alias = parts[1];
        } else {
            table = src;
            alias = null;
        }
        return new TableSource(table, alias);
    }

    public String getTable() {
        return table;
    }

    public String getAlias() {
        return alias;
    }

    @Override
    public String toString() {
        if (alias != null) {
            return table + " " + alias;
        }
        return table;
    }

    public String getSelectTable() {
        if (alias == null) {
            return table;
        }
        return table + " " + alias;
    }

    public boolean match(String tableName) {
        if (table.equalsIgnoreCase(tableName)) {
            return true;
        }
        if (alias != null) {
            return alias.equalsIgnoreCase(tableName);
        }
        return false;
    }
}
